/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.web;

import com.iwindplus.boot.web.domain.property.FilterProperty;
import com.iwindplus.boot.web.domain.property.HttpClientProperty;
import com.iwindplus.boot.web.interceptor.RestTemplateInterceptor;
import com.iwindplus.boot.web.manager.http.RestTemplateManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate配置.
 *
 * @author zengdegui
 * @since 2023/08/31
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({HttpClientProperty.class, FilterProperty.class})
@ConditionalOnProperty(prefix = "rest.client", name = "enabled", havingValue = "true", matchIfMissing = true)
public class RestTemplateConfiguration {

    @Resource
    private CloseableHttpClient closeableHttpClient;

    /**
     * 创建 RestTemplate.
     *
     * @param restTemplateInterceptor RestTemplate拦截器
     * @return RestTemplate
     */
    @Bean
    public RestTemplate restTemplate(RestTemplateInterceptor restTemplateInterceptor) {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(this.closeableHttpClient);
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        restTemplate.getInterceptors().add(restTemplateInterceptor);
        log.info("RestTemplate={}", restTemplate);
        return restTemplate;
    }

    /**
     * 创建 RestTemplateInterceptor.
     *
     * @return RestTemplateInterceptor
     */
    @Bean
    public RestTemplateInterceptor restTemplateInterceptor() {
        RestTemplateInterceptor restTemplateInterceptor = new RestTemplateInterceptor();
        log.info("RestTemplateInterceptor={}", restTemplateInterceptor);
        return restTemplateInterceptor;
    }

    /**
     * 创建 RestTemplateManager.
     *
     * @return RestTemplateManager
     */
    @Bean
    @ConditionalOnBean(RestTemplate.class)
    public RestTemplateManager restTemplateManager() {
        RestTemplateManager restTemplateManager = new RestTemplateManager();
        log.info("RestTemplateManager={}", restTemplateManager);
        return restTemplateManager;
    }
}
